<template>
  <div class="nva_menu_container">
    <!-- 列表页面 -->
    <div class="container" ref="container" v-if="show"  @click="showIdex=null">
      <p class="title">管理员管理</p>
      <div class="info-search">
        <label for="">
          管理员姓名:
          <input type="text" v-model="search.userName">
        </label>
        <label for="">
          管理员角色:
          <el-select v-model="search.roleId" placeholder="请选择" size="middle" class="diy-input">
            <el-option
              label="请选择"
              value=""
            >
            </el-option>
            <el-option
              v-for="item in role"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId">
            </el-option>
          </el-select>
        </label>
        <label for="">
          所在学校:
          <input type="text" v-model="search.schoolName">
        </label>
        <a href="javascript:;" class="save" @click="seachResult">搜索</a>
      </div>
      <div class="operation">
        <a href="javascript:;" class="save" @click="addUser">新增管理员</a>
        <a href="javascript:;" class="save" @click="dialogVisible = true">导入管理员</a>
      </div>
      <table class="table" border="1" cellspacing="0" cellpadding="0" borderColor="#e0e0e0">
        <thead>
          <tr>
            <td>管理员姓名</td>
            <td>管理员角色</td>
            <td>管理员账号</td>
            <td>所在区域</td>
            <td>所在学校</td>
            <td>是否为考点</td>
            <td>考点代码</td>
            <td>操作</td>
          </tr>
        </thead>
        <tbody v-if="userList.length">
          <tr v-for="(item,i) in userList" :key="i" :class="[item.status ==1 ? 'ban':'']">
            <td>{{item.userName}}</td>
            <td>{{item.sysRoles.length?item.sysRoles[0].roleName:''}}</td>
            <td>{{item.loginName}}</td>
            <td>{{item.county}}</td>
            <td>{{item.schoolName}}</td>
            <td>{{item.areaTree?(item.areaTree.isPoint=='0'?'是':'否'):''}}</td>
            <td>{{item.areaTree.isPoint=='0'?item.areaTree.areaCode: ''}} </td>
            <td>
              <a href="javascript:;" @click="showView(item)">查看</a>
              <a href="javascript:;" @click="editUser(item)" >编辑</a>
              <a href="javascript:;"   @click="deleteUser(item, 'delete')">删除</a>
              <a href="javascript:;" v-if="item.status"  @click="deleteUser(item, 'unban')">解冻</a>
              <a href="javascript:;" v-else @click="deleteUser(item, 'ban')">冻结</a>
            </td>
          </tr>
        </tbody>
        <tbody v-else>
          <tr>
            <td colspan="8">
              <p>未找到任何数据</p>
            </td>
          </tr>
        </tbody>
      </table>
      <!-- <div class="page">
        <label for="">
          每页显示
          <select name="" id="">
            <option value="5">
              5
            </option>
            <option value="5">
              10
            </option>
            <option value="5">
              20
            </option>
            <option value="5">
              50
            </option>
          </select>
          共235条数据
        </label>

        <div class="page-num">
          <div class="page-text">
            <i class="el-icon-arrow-left"></i>
            <span>1/23</span>
            <i class="el-icon-arrow-right"></i>
          </div>
          <input class="diy-input" type="text" placeholder="页码数"/>
          <div class="to-page">
            <i class="el-icon-caret-right"></i>
          </div>
        </div>
      </div> -->
      <pagination v-if="userList.length" :listQuery="page" @changeCurrentPage="changeCurrentPage"></pagination>
      <!-- 导入管理员 -->
      <el-dialog
        title="导入管理员"
        :visible.sync="dialogVisible"
        width="30%"
        center>
          <el-upload
          class="upload-demo"
          :action="GLOBAL.COMMON"
          ref="upload"
          :limit="1"
          :auto-upload="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <a :href='GLOBAL.COMMON+"/sysuser/download_template"' class="download">导入模板下载</a>
          <span class="fuzhu"></span>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="uploadUser">确 定</el-button>
          </span>
      </el-dialog>
      <!-- 查看 -->
      <el-dialog
        title="查看管理员信息"
        :visible.sync="viewDialogVisible"
        width="30%"
        center>
        <div class="show-content">
          <p><span>管理员姓名：</span><span>{{showForm.userName}}</span></p>
          <p><span>管理员角色：</span><span>{{showForm.sysUserName}}</span></p>
          <p><span>管理员账号：</span><span>{{showForm['loginName']}}</span></p>
          <p><span>所在区域：</span><span>{{showForm.countyName}}</span></p>
          <p><span>所在学校：</span><span>{{showForm.schoolName}}</span></p>
          <p><span>考点代码：</span><span>{{showForm.isPoint=='0'?showForm.areaCode:''}}</span></p>
          <p><span>联系电话：</span><span>{{showForm.phonenumber}}</span></p>
          <p><span>电子邮箱：</span><span>{{showForm.email}}</span></p>
        </div>
        <span class="fuzhu"></span>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="viewDialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>
      <!--删除提示  -->
      <el-dialog
        title="提示"
        :visible.sync="isDelete"
        width="30%"
        center>
        <p>{{title}}</p>
        <span class="fuzhu"></span>
        <span slot="footer" class="dialog-footer">
          <el-button  @click="isDelete = false">取消</el-button>
          <el-button type="primary" @click="handleDelete">确定</el-button>
        </span>
      </el-dialog>
    </div>
    <!--新增页面 -->
    <div class="container" ref="container" v-else>
      <a class="back" @click="show=true;getUser()"><i class="el-icon-back"></i><span>返回</span></a>
      <P class="middle-font">{{addTitle}}</P>
      <el-form ref="form" :model="form" label-width="140px" style="width:60%" class="c-form">
        <el-form-item label="管理员姓名">
          <el-input v-model="form.userName" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="管理员账号">
          <el-input v-model="form.loginName" :disabled="op==1" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="form.password" @focus="form.password=''" clearable></el-input>
        </el-form-item>
        <el-form-item label="所在学校">
          <!-- <p>{{schollName}}</p> -->
          <el-select v-model="form.areaId" placeholder="请选择所在学校" style="width:100%">
            <el-option v-for="(item,idx) in list" :key="idx" :label="item.areaName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="form.phoneNumber" clearable></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱">
          <el-input v-model="form.email" clearable></el-input>
        </el-form-item>
      </el-form>
      <span class="fuzhu"></span>
      <div class="btn">
        <a href="javascript:;" class="save" @click="saveUser">确定</a>
        <a href="javascript:;" class="cancel" @click="show=true;getUser()">取消</a>
      </div>
    </div>
  </div>
</template>

<script>
// import contSidebar from '@/components/navSidebar.vue'
import pagination from '@/components/Pagination.vue'
import axios from 'axios'
export default {
  data () {
    return {
      userList: [],
      dialogVisible: false,
      viewDialogVisible: false,
      isDelete: false,
      form: {
        userName: '',
        loginName: '',
        password: '',
        phoneNumber: '',
        email: '',
        areaId: this.areaId
      },
      list: [
      ],
      // activeItem: 1,
      schollName: '',
      show: true,
      showForm: {},
      search: {
        roleId: '',
        schoolName: '',
        userName: ''
      },
      role: [],
      op: 0,
      area: '',
      temp: {},
      page: {
        page: 1,
        pageSize: 10,
        total: null,
        totalPages: null
      },
      title: '',
      userInfo: {},
      areaId: '',
      addTitle: '新增管理员'
    }
  },
  methods: {
    // 新增
    addUser () {
      this.op = 0
      this.show = false
      this.addTitle = '新增管理员'
      this.form = {
        userName: '',
        areaId: '',
        loginName: '',
        password: '',
        phoneNumber: '',
        email: ''
      }
    },
    // 编辑
    editUser (item) {
      this.addTitle = '编辑管理员'
      this.op = 1
      this.show = false
      this.form.userName = item.userName
      this.form.loginName = item.loginName
      this.form.password = item.password ? item.password : '******'
      this.form.phoneNumber = item.phonenumber
      this.form.email = item.email
      this.form.id = item.userId
      this.form.areaId = item.areaTree.id
      // // 暂存用户名和密码
      this.temp.password = '******'
    },
    // 保存用户信息
    saveUser () {
      console.log(this.form)
      if (this.op) {
        // 编辑操作
        this.$http.updateUser({
          email: this.form.email,
          id: this.form.id,
          phoneNumber: this.form.phoneNumber,
          userName: this.form.userName
        }).then(res => {
          if (res.code === 20000) {
            if (this.temp.password === this.form.password) {
              this.$message.success('修改成功！')
              this.show = true
              this.getUser()
            } else {
              this.$http.updatePassword({
                id: this.form.id,
                password: this.form.password
              }).then(res => {
                if (res.code === 20000) {
                  this.$message.success('修改成功！')
                  this.show = true
                  this.getUser()
                } else {
                  this.$message.error(res.msg)
                }
              })
            }
          }
        })
      } else {
        // 添加操作
        this.$http.createUser(this.form).then(res => {
          if (res.code === 20000) {
            this.$message.success('添加成功！')
            this.show = true
            this.getUser()
          } else {
            this.$message.error(res.msg)
          }
        })
      }
    },
    // 页面初始化
    async initData () {
      // 获取一下当前用户的角色
      // this.area = JSON.parse(sessionStorage.getItem('area'))
      // this.area = sessionStorage.getItem('area')
      // console.log('list', this.area)
      // // 获取区域信息
      let res = await this.$http.getArea()
      if (res.code === 20000) {
        let obj = res.data.child
        this.list = []
        for (let i = 0; i < obj.length; i++) {
          if (obj[i].areaName === sessionStorage.getItem('countyName')) {
            this.areaId = obj[i].id
            this.list = obj[i].child
          }
        }
      }

      // 获取管理员列表
      this.getUser()
    },
    // 获取用户
    async getUser () {
      let result = await this.$http.getAdmin({
        areaId: this.areaId,
        pageNum: this.page.page,
        pageSize: this.page.pageSize,
        roleId: this.search.roleId,
        schoolName: this.search.schoolName,
        userName: this.search.userName
      })
      if (result.code === 20000) {
        this.userList = result.data.data
        this.page.totalPages = result.data.pageInfo.pageTotal
        this.page.total = result.data.pageInfo.totalSize
      } else {
        this.$message.error(result.msg)
      }
    },
    // 查看
    showView (item) {
      this.showForm = item
      this.showForm.sysUserName = item.areaTree.sysUserName
      this.showForm.areaCode = item.areaTree ? item.areaTree.areaCode : ''
      this.viewDialogVisible = true
    },
    // 搜索
    async seachResult () {
      // 初始化分页信息
      this.page = {
        page: 1,
        pageSize: 10,
        total: null,
        totalPages: null
      }

      let result = await this.$http.getAdmin({
        areaId: this.areaId,
        roleId: this.search.roleId,
        schoolName: this.search.schoolName,
        userName: this.search.userName,
        pageNum: this.page.page,
        pageSize: this.page.pageSize
      })
      if (result.code === 20000) {
        this.userList = result.data.data
        this.page.totalPages = result.data.pageInfo.pageTotal
        this.page.total = result.data.pageInfo.totalSize
        this.activeItem = null
      } else {
        this.$message.error(result.msg)
      }
    },
    // 分页回调接收参数
    changeCurrentPage (queryData) {
      this.page.page = queryData.page
      this.page.pageSize = queryData.pageSize
      this.getUser()
    },
    // 删除用户
    deleteUser (item, str) {
      this.userInfo = item
      this.userInfo.state = str
      if (str === 'delete') {
        this.title = '您是否确认删除该用户？'
      } else if (str === 'ban') {
        this.title = '您是否确认冻结该用户？'
      } else if (str === 'unban') {
        this.title = '您是否确认解冻该用户？'
      }
      this.isDelete = true
    },
    // 确认删除回调
    async handleDelete () {
      console.log('this item', this.userInfo)
      this.loading = true
      let res = await this.$http.changeStatus({
        id: this.userInfo.userId,
        operation: this.userInfo.state
      })
      if (res.code === 20000) {
        this.$message.success('修改用户成功！')
        this.isDelete = false
        this.getUser()
      } else {
        this.$message.error(res.msg)
        this.isDelete = false
      }
      this.loading = false
    },
    uploadUser () {
      var obj = this.$refs.upload.uploadFiles[0] ? this.$refs.upload.uploadFiles[0].raw : ''
      var data = new FormData()
      data.append('file', obj)
      if (obj) {
        axios.post(`${this.GLOBAL.COMMON}/sysuser/import`, data, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then((res) => {
          console.log('res', res)
          if (res.data.code === 20000) {
            this.$message.success('管理员批量导入成功！')
            this.dialogVisible = false
            this.getUser()
          } else {
            this.$message.error(res.data.msg)
            this.dialogVisible = false
          }
        })
      } else {
        this.$message.error('请先选择文件！')
      }
    }
  },
  components: {
    pagination
  },
  mounted () {
    this.initData()
    this.$http.getALLRoles().then(res => {
      if (res.code === 20000) {
        for (let i = 0; i < res.data.length; i++) {
          if (res.data[i].roleKey === 'city' || res.data[i].roleKey === 'county' || res.data[i].roleKey === 'mark_teacher') {

          } else {
            this.role.push(res.data[i])
          }
        }
      } else {
        this.$message.error(res.msg)
      }
    })
  }
}
</script>

<style lang="stylus" scoped>
color = #4177ff
background = #f3f3f3
@import url('../../assets/styles/base.css');
.container
  width: calc(100% - 50px)
  margin-left: 0
  .operation
    a
      padding 4px 6px
      width auto
  .info-search
    input
      font-size 12px
  .exam-info
    width 100%
    height 48px
    line-height 48px
    background #3d68d5
    position: relative;
    top: 26px;
    p
      span
        margin-left 20px
        color #fff
        font-size 12px
        font-weight bold
      a
        float right
        margin-right 40px
        color #fff
        font-size 12px
        text-decoration none
  .table
    width 100%
    margin-top 25px
    text-align center
    td
      border 1px solid #e0e0e0
      text-align center
      line-height 48px
    thead
      tr
        background background
        td
          height 48px
          font-weight bold
    tbody
      tr
        &.ban
          background #f5f5f5
        &:hover
          background #f9faff
        td
          height 46px
          font-size 14px
          a
            font-size 12px
            color #555
            text-decoration none
            padding-left 6px
            &:hover
              color #4177ff
.download
    float: right;
    margin-top: -23px
    color color
    text-decoration none
.show-content
  width 70%
  margin-left 30px
  p
    font-weight bold
    line-height 30px
    span
      margin-right 10px
      color #999
      font-weight normal
      &:nth-child(1)
        display inline-block
        width 100px
      &:nth-child(2)
        font-weight bold
        color #333
</style>

<style>
  .el-upload-list.el-upload-list--text {
    display: block;
    float: right;
    margin-right: 256px;
    margin-top: -6px;
  }
</style>

<style lang="stylus" scoped>
color = #4177ff
background = #f3f3f3
  .back
    cursor pointer
    font-size 14px
    color color
    span
      margin-left 10px
  .big-font
    font-size 18px
    font-weight bold
  .middle-font
    line-height 46px
    font-size 16px
    font-weight bold
  .ann
    color #e0e0e0
    .diy-input
      width 58px
      height 30px
      line-height 30px
      font-size 18px
      border-radius 5px
      border 1px solid #e0e0e0
      margin 0 6px
      text-align center
  .btn
    margin-top 40px
    a
      display inline-block
      width 70px
      height 38px
      text-align center
      line-height 38px
      border-radius 5px
      color #fff
      text-decoration none
      margin-right 14px
      &.save
        background color
      &.cancel
        color color
        border 1px solid color
  .fuzhu
    top 10px
</style>

<style>
  .info-search label .diy-input input.el-input__inner {
    font-size: 12px;
  }
  .el-upload-list {
    display: block !important;
  }
  .el-upload-list__item-name {
    margin-right: 20px;
  }
</style>
